package fun.ticsmyc.rpc.server.transport.netty.codec;

import fun.ticsmyc.rpc.common.entity.RpcResponse;
import fun.ticsmyc.rpc.common.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Ticsmyc
 * @date 2020-10-26 10:42
 */
public class ResponseEncoder extends MessageToByteEncoder<RpcResponse<Object>> {
    private static final Logger logger = LoggerFactory.getLogger(ResponseEncoder.class);

    private final int MAGIC_NUMBER = 0xCAFEBABE;
    private final byte CURRENT_PROTOCOL_VERSION = 1;

    private Serializer serializer;
    public ResponseEncoder(Serializer serializer){
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcResponse<Object> msg, ByteBuf out){
        byte[] response = serializer.serialize(msg);

        //魔数
        out.writeInt(MAGIC_NUMBER);
        //协议版本
        out.writeByte(CURRENT_PROTOCOL_VERSION);
        //序列化器编号
        out.writeByte(serializer.getId());
        //消息体长度和消息体
        out.writeInt(response.length);
        out.writeBytes(response);
        logger.debug("响应包大小："+(response.length+10));
    }
}


